#!/bin/bash
function escape(){
  local originalString=$1
  echo $originalString|sed 's/\"/\\"/g'
}
function createField (){
  local fieldName="$1"
  local fieldValue="$2"
  local result=( $(escape "$fieldValue" ) )
  local value=`echo ${result[@]}`
  echo "\"$fieldName\": \"$value\""
}

function createArrayField (){
  local fieldName=$1
  local fieldElements=$2
  local index=0
  local value=""
  for i in $fieldElements; do
      if [ ${index} -gt 0 ]; then
         value=${value}","
      fi
      value=${value}${i}
      index=$((index+1));
  done;
   if [ "$value" != "" ]; then
     value="["${value}"]"
  else
     value="[]"
  fi

  echo "\"$fieldName\": ${value}"
}
function createRowElement (){
  local elements=$*
  local value="";
  local index=0
  for i in $elements; do
      if [ ${index} -gt 0 ]; then
         value=${value}","
      fi
      local result=( $(escape "$i" ) )
      value=${value}"\""${result}"\""
      index=$((index+1));
  done;
  if [ "$value" != "" ]; then
     value="["${value}"]"
  else
     value="[]"
  fi
  echo $value
}

function addFieldToJsonObject(){
  local initialObject="$1"
  local newField="$2"
  local value=""
  if [ "$initialObject" != "" ]; then
     local length=${#initialObject}
     length=$((${length}-2))
     initialObject=${initialObject:1:$length}
  fi
  if [ "$newField" != "" ]; then
     if [ "$initialObject" != "" ]; then
        value="${initialObject}, ${newField}"
     else
        value=$newField
     fi
  else
    value=${initialObject}
  fi
  echo "{"${value}"}"
}